package com.jiepos.mpos.biz.service.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.common.constant.DBConstant;
import com.jiepos.mpos.common.constant.DBConstant.Table;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.ServiceInfDao;
import com.jiepos.mpos.common.entity.App_Service_InfEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.DateUtil;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.StringUtils;

/**
 * 业务维护Service
 * @author Zhao.Jinkui
 * @version 1.0
 * @ProjectName: mpos
 * @Package com.jiepos.mpos.biz.service.service
 * @ClassName ServiceInfService
 * @history
 * @UpdateRemark []
 * @since 2017/9/24
 */
@Service
public class ServiceInfService extends BaseService{

    @Autowired
    private ServiceInfDao serviceInfDao;

    /**
     * 根据条件分页查询业务信息
     * @param pagination 分页组件
     * @param entity 查询参数实体
     * @return
     */
    public Map findByCondition(Pagination pagination, App_Service_InfEntity entity){

        StringBuffer sqlBuf =  getInitSql("").append(", ");
            sqlBuf.append(" SERVICE_UUID AS UUID, ")
                .append("        SERVICE_NO, ")
                .append("        SERVICE_NAME, ")
                .append("        BEGDATE, ")
                .append("        BEGTIME, ")
                .append("        ENDDATE, ")
                .append("        ENDTIME, ")
                .append("        SERVICE_ST || '-' || ")
                .append("        (SELECT CODE_DESC ")
                .append("           FROM "+ DBConstant.Table.T_APP_CODE_LIST)
                .append("          WHERE CODE_TP =  '"+ DBConstant.Code.SERVICE_ST+"'")
                .append("            AND SERVICE_ST = CODE_VAL) AS SERVICE_ST, ")
                .append("        SERVICE_TYPE || '-' || ")
                .append("        (SELECT CODE_DESC ")
                .append("           FROM "+ DBConstant.Table.T_APP_CODE_LIST)
                .append("          WHERE CODE_TP = '"+DBConstant.Code.SERVICE_TYPE+"'")
                .append("            AND SERVICE_TYPE = CODE_VAL) AS SERVICE_TYPE, ")
                .append("        REC_ID, ")
                .append("        REC_ST, ")
                .append("        LAST_OPER_IN ")
                .append("   FROM  "+DBConstant.Table.T_APP_SERVICE_INF)
                .append("   WHERE 1=1 ");
        //参数集合
        List<String> params = new ArrayList<>();
        if(!StringUtils.isBlank(entity.getService_no())){
            sqlBuf.append("   AND SERVICE_NO LIKE ? ");
            params.add("%"+entity.getService_no()+"%");
        }
        if(!StringUtils.isBlank(entity.getService_name())){
            sqlBuf.append("   AND SERVICE_NAME LIKE ? ");
            params.add("%"+entity.getService_name()+"%");
        }
        if(!StringUtils.isBlank(entity.getService_st())){
            sqlBuf.append("   AND SERVICE_ST = ? ");
            params.add(entity.getService_st());
        }
        if(!StringUtils.isBlank(entity.getService_type())){
            sqlBuf.append("   AND SERVICE_TYPE = ? ");
            params.add(entity.getService_type());
        }
        pagination.queryString = sqlBuf.toString();
        pagination = this.getOrderSql(pagination,null);
        //执行查询
        return serviceInfDao.getPaginationMap(pagination,"",params);
    }


    /**
     * 查询所有业务名
     * @return UUID和业务名称
     */
    public List findAllServiceName(String service_uuid){
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT SERVICE_UUID, ")
                .append("  SERVICE_NO||'-'||SERVICE_NAME AS SERVICE_NAME  ")
                .append("  FROM T_APP_SERVICE_INF ")
                .append("   WHERE 1 = 1 ");
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        list = serviceInfDao.queryForList(sqlBuf.toString(), null);
        if(!StringUtils.isBlank(service_uuid)){
            boolean flag = false;
            for(Map<String,Object> map : list){
                for(Map.Entry entry : map.entrySet()){
                    if(service_uuid.equals(entry.getValue())){
                        map.put("selected",true);
                        flag = true;
                        break;
                    }
                }
                if(flag){
                    break;
                }
            }
        }
        Map<String, Object> topMap = new HashMap<String, Object>();
        topMap.put("SERVICE_UUID", "");
        topMap.put("SERVICE_NAME", "---请选择---");
        list.add(0, topMap);
        return list;
    }

    /**
     * 根据UUID加载唯一业务信息
     * @param
     * @return
     */
    public App_Service_InfEntity findByUUID(String service_uuid){
        App_Service_InfEntity entity = serviceInfDao.findByParam("service_uuid", service_uuid);
        if(!StringUtils.isBlank(entity.getBegdate())){
            entity.setBegdate(DateUtil.toString(DateUtil.strToDate(entity.getBegdate(),"yyyyMMdd"),"yyyy-MM-dd"));
        }
        if(!StringUtils.isBlank(entity.getBegtime())){
            entity.setBegtime(DateUtil.toString(DateUtil.strToDate(entity.getBegtime(),"HHmmss"),"HH:mm:ss"));
        }
        if(!StringUtils.isBlank(entity.getEnddate())){
            entity.setEnddate(DateUtil.toString(DateUtil.strToDate(entity.getEnddate(),"yyyyMMdd"),"yyyy-MM-dd"));
        }
        if(!StringUtils.isBlank(entity.getEndtime())){
            entity.setEndtime(DateUtil.toString(DateUtil.strToDate(entity.getEndtime(),"HHmmss"),"HH:mm:ss"));
        }
        return entity;
    }

    /**
     * 保存业务信息(新增、修改)
     * @param entity
     * @param map
     */
    public void saveServiceInf(App_Service_InfEntity entity,Map map){
        //时期及时间处理
        entity.setBegdate(DateUtil.toString(DateUtil.strToDate(entity.getBegdate(),"yyyy-MM-dd"),"yyyyMMdd"));
        entity.setBegtime(DateUtil.toString(DateUtil.strToDate(entity.getBegtime(),"HH:mm:ss"),"HHmmss"));
        entity.setEnddate(DateUtil.toString(DateUtil.strToDate(entity.getEnddate(),"yyyy-MM-dd"),"yyyyMMdd"));
        entity.setEndtime(DateUtil.toString(DateUtil.strToDate(entity.getEndtime(),"HH:mm:ss"),"HHmmss"));
        //以是否有uuid来区分操作
        if (!StringUtils.isBlank(entity.getService_uuid())) {
            //更新
            entity = (App_Service_InfEntity) this.saveCommonData(entity,map,"update");
            List noChangeList = new ArrayList();
            noChangeList.add("service_uuid");
            noChangeList.add("rec_crt_ts");
            serviceInfDao.update(entity,noChangeList);
        }else{
            //新增
            entity = (App_Service_InfEntity) this.saveCommonData(entity, map, null);
            entity.setService_uuid(IDFactoryUtil.getUUID());
            serviceInfDao.save(entity);
        }

    }

    /**
     * 启用、冻结业务
     * @param serviceSt
     * @param service_uuids
     * @param loginUser
     */
    public void updateServiceSt(String serviceSt, String service_uuids, Map loginUser){
        serviceInfDao.updateByIds("service_uuid", service_uuids, serviceSt,
                String.valueOf(loginUser.get(SystemConstant.SESSION_LOGIN_USER)));
    }

    /**
     * 检查业务是否存在(编号及名称)
     * @param entity
     * @return
     */
    public String checkService(App_Service_InfEntity entity){
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT SERVICE_UUID ")
                .append("   FROM ")
                .append(DBConstant.Table.T_APP_SERVICE_INF)
                .append("  WHERE 1=2 ");

        //参数集合
        List<String> params = new ArrayList<>();
        if(!StringUtils.isBlank(entity.getService_no())){
            sqlBuf.append("  OR SERVICE_NO = ? ");
            params.add(entity.getService_no());
        }
        if(!StringUtils.isBlank(entity.getService_name())){
            sqlBuf.append("     OR SERVICE_NAME = ? ");
            params.add(entity.getService_name());
        }
        if(params.size() > 0){
            List list = serviceInfDao.queryForList(sqlBuf.toString(),params);
            if(list!=null && list.size() > 0){
                //有重复的编号和名称，分情况判断：
                if(StringUtils.isBlank(entity.getService_uuid())){
                    //说明是新增操作，不能进行保存
                    return SystemConstant.ERROR;
                }else{
                    //说明是修改操作，分情况判断
                    if(list.size() == 1){
                        //修改后有冲突，判断是不是自己
                        Map<String, Object> map = (Map<String, Object>) list.get(0);
                        if(entity.getService_uuid().equals(String.valueOf(map.get("SERVICE_UUID")))){
                            //说明是自己
                            return SystemConstant.SUCCESS;
                        }else{
                            //不是自己
                            return SystemConstant.ERROR;
                        }
                    }else{
                        //list.size() > 1 说明修改后跟别的业务冲突，不能进行保存
                        return SystemConstant.ERROR;
                    }
                }
            }else{
                //无重复的编号和名称 可以进行保存操作
                return SystemConstant.SUCCESS;
            }
        }
        return SystemConstant.SUCCESS;
    }
    
    
    /**
     * 获取业务树
     * @return
     */
    public List<Map<String, Object>> getServiceInfTree(){
    	StringBuffer sb = new StringBuffer();
    	sb.append("select t1.service_uuid as \"id\",null as \"pId\",t1.service_no||'-'||t1.service_name as \"name\" from ");
    	sb.append(Table.T_APP_SERVICE_INF).append(" t1 where 1=1 ");
    	List<Map<String, Object>> serList = serviceInfDao.queryForList(getOrderSql(sb.toString(), "t1"));
    	
    	StringBuffer serUuids = new StringBuffer();
		for(Map<String, Object> menu : serList){
			serUuids.append("'").append(menu.get("id")).append("'").append(",");
		}
		
		sb = new StringBuffer();
		sb.append("select service_param_uuid as \"id\",service_uuid as \"pId\",PARAM_NO||'-'||PARAM_NAME as \"name\",'p' as \"flag\" from ");
		sb.append(Table.T_APP_SERVICE_PARAM);
		sb.append(" WHERE service_uuid IN (").append(serUuids.substring(0, serUuids.length()-1)).append(")");
		List<Map<String, Object>> paramList = serviceInfDao.queryForList(getOrderSql(sb.toString(), null));
		
		serList.addAll(paramList);		
		return serList;    	
    }
    
    /**
     * 根据业务编号查询
     * @param service_no
     * @return
     */
    public String findUuidByNo(String service_no){    	
    	if (StringUtils.isBlank(service_no) || service_no.equals("undefined")) {
			return "";
		}
        App_Service_InfEntity entity = serviceInfDao.findByParam("service_no", service_no);
        if(entity!=null){
        	return entity.getService_uuid();
        }
        return "";
    }

    /**
     * 根据业务UUID得到业务的类型
     * @param service_uuid
     * @return
     */
    public String getServiceTypeByServiceUUID(String service_uuid){
        if(StringUtils.isBlank(service_uuid)){
            return null;
        }
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT SERVICE_TYPE ")
                .append("   FROM T_APP_SERVICE_INF T ")
                .append("  WHERE T.SERVICE_UUID = ? ")
                .append("    AND REC_ST != '0' ");
        List<String> params = new ArrayList<>();
        params.add(service_uuid);
        List<Map<String,Object>> list = serviceInfDao.queryForList(sqlBuf.toString(), params);
        if(list != null && list.size()>0 && list.get(0).get("SERVICE_TYPE")!=null){
            return StringUtils.objToString(list.get(0).get("SERVICE_TYPE"));
        }else{
            return null;
        }
    }

}
